/**
 * @desc 入口文件
 */
import { Layer } from './layer'
import { Rectangle } from './rectangle'
import { History } from './history'
import { Serializer } from './serializer'
import { Application, Container } from 'pixi.js'
import { Log } from './Log'
class PixiApp {
  constructor(element, option) {
    // 初始化画布
    let options = {
      width: window.innerWidth,
      height: window.innerHeight,
      backgroundColor: 0x1099bb,
      resolution: window.devicePixelRatio || 1,
      antialias: true,
      ...option
    }
    if (element instanceof Element) {
      this.app = new Application(options)
      element.appendChild(this.app.view)
      // 添加容器
      this.layerContainer = new Container()
      this.app.stage.addChild(this.layerContainer)
      // 图层
      this.layers = [new Layer(), new Layer()]
      this.layers.forEach((layer) =>
        this.layerContainer.addChild(layer.container)
      )
      // 导出JSON
      this.serializer = new Serializer(this.layerContainer)
      // 历史，撤回，重做
      this.history = new History()
      // 事件监听
      this.setupEventListeners()
    } else {
      Log.error("Is not Element DOM Please use document.querySelector('#id')")
    }
  }

  setupEventListeners() {
    // 设置按钮事件监听器
    const createRectangleButton = document.getElementById('create-rectangle')
    const undoButton = document.getElementById('undo')
    const redoButton = document.getElementById('redo')
    const exportJsonButton = document.getElementById('export-json')
    const importJsonButton = document.getElementById('import-json')

    createRectangleButton.addEventListener('click', () =>
      this.createRandomRectangle()
    )
    undoButton.addEventListener('click', () => this.history.undo())
    redoButton.addEventListener('click', () => this.history.redo())
    exportJsonButton.addEventListener('click', () =>
      console.log(this.serializer.exportToJson(), '------exportToJson----')
    )
    // importJsonButton.addEventListener("click", () =>
    //   this.serializer.importFromJson()
    // );
    this.serializer
  }

  createRandomRectangle() {
    const color = Math.random() * 0xffffff
    const x = Math.random() * (this.app.view.width - 100)
    const y = Math.random() * (this.app.view.height - 100)
    const rectangle = new Rectangle(color, x, y, this.history)
    const layer = this.layers[Math.floor(Math.random() * this.layers.length)]
    layer.addRectangle(rectangle)
  }
}

export { PixiApp }
